<template>
  <!-- 组织机构选择插件 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :model-value="visible"
      :title="title"
      width="1200px"
      draggable
      destroy-on-close
      align-center
      @close="closeDialog"
      class="personDialog"
      append-to-body
    >
      <el-row :gutter="10">
        <!-- 用户列表 -->
        <el-col :span="19">
          <div>
            <el-form
              ref="queryFormRef"
              :model="searchParam"
              :inline="true"
              label-width="76px"
              label-position="left"
            >
              <!-- <el-form-item label="物料组">
                <el-select
                  v-model="searchParam.materialGroupId"
                  placeholder="请选择物料组"
                  clearable
                >
                  <el-option
                    v-for="item in materialGroupTree"
                    :key="item.id"
                    :label="item.materialGroupName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="物料类型">
                <el-select
                  v-model="searchParam.materialType"
                  placeholder="请选择物料类型"
                  clearable
                >
                  <el-option
                    v-for="item in isList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item> -->
              <el-form-item label="存货编码">
                <el-input
                  v-model="searchParam.materialCode"
                  placeholder="请输入物料编号"
                  clearable
                  @keyup.enter="search"
                />
              </el-form-item>
              <el-form-item label="物料名称">
                <el-input
                  v-model="searchParam.materialName"
                  placeholder="请输入物料名称"
                  clearable
                  @keyup.enter="search"
                />
              </el-form-item>
              <el-form-item label="物料图号">
                <el-input
                  v-model="searchParam.figureNumber"
                  placeholder="请输入物料图号"
                  clearable
                  @keyup.enter="search"
                />
              </el-form-item>
              <el-form-item class="ml-[5px]">
                <el-button type="primary" @click="search"
                  ><i-ep-search />搜索</el-button
                >
                <el-button @click="resetParams">
                  <i-ep-refresh />重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- <el-card
            shadow="never"
            class="table-container card-table-p15 h-[536px]"
          > -->
          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="tableData"
            @select="handleSelectionChange"
            @select-all="handleAllChange"
            height="460px"
            border
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="存货编码"
              prop="materialCode"
              min-width="100"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column
              label="物料名称"
              prop="materialName"
              min-width="100"
              show-overflow-tooltip
              align="left"
            >
              <template #default="scope">
                <span style="text-align: left">
                  {{ scope.row.materialName }}</span
                >
              </template>
            </el-table-column>
            <el-table-column
              label="物料类型"
              prop="materialType"
              min-width="100"
              show-overflow-tooltip
              align="left"
            >
              <template #default="scope">
                {{ useDictionary("MaterialType", scope.row.materialType) }}
              </template>
            </el-table-column>
            <el-table-column
              label="物料图号"
              prop="figureNumber"
              min-width="150"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column
              label="物料组"
              prop="materialGroupName"
              min-width="100"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column
              label="短号"
              prop="shortCode"
              min-width="100"
              show-overflow-tooltip
              align="left"
            />

            <el-table-column
              label="外来编号"
              prop="srcCode"
              min-width="100"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column
              label="国产件标识"
              prop="lcCkd"
              min-width="100"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.lcCkd === 1">是</el-tag>
                <el-tag type="info" v-else>否</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="物料状态"
              prop="materialState"
              min-width="90"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ useDictionary("MaterialState", scope.row.materialState) }}
              </template>
            </el-table-column>
            <el-table-column
              label="物料规格"
              prop="materialSpecification"
              min-width="100"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column
              label="计量单位"
              prop="unit"
              min-width="90"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ useDictionary("MeasurementUnit", scope.row.unit) }}
              </template>
            </el-table-column>
            <el-table-column
              label="毛重"
              prop="roughWeight"
              min-width="100"
              show-overflow-tooltip
              align="left"
            />
          </el-table>

          <el-pagination
            small
            background
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :total="pageable.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <!-- </el-card> -->
        </el-col>
        <!-- 回显树 -->
        <el-col
          :span="5"
          style="box-shadow: 0px 0px 12px rgba(3, 8, 72, 0.08)"
          class="!p-[0px] h-auto"
        >
          <div>
            <el-row class="p-[15px]">
              <el-col :span="18">
                <div class="selectText">
                  已选个数(<span style="color: #0080ff">{{
                    totalMultipleSelection.length
                  }}</span
                  >)
                </div>
              </el-col>
              <el-col :span="6" align="right">
                <el-button size="small" type="danger" @click="delAll" link
                  >清空</el-button
                >
              </el-col>
            </el-row>

            <el-scrollbar height="480px">
              <div>
                <el-row
                  v-for="(item, index) in totalMultipleSelection"
                  :key="index"
                  class="hover-b-blue ml-[8px] mr-[8px] pl-[14px] pr-[14px] name"
                >
                  <el-col :span="20">物料{{ item.materialCode }}</el-col>
                  <el-col :span="4" align="right">
                    <i-ep-CircleCloseFilled
                      class="c-[rgba(0,0,0,.15)]"
                      @click="delSingle(item, index)"
                    />
                  </el-col>
                </el-row>
              </div>
            </el-scrollbar>
          </div>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import { ElTable } from "element-plus";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入

const dictionaryStore = useDictStoreHook();
defineOptions({
  name: "UpUserOrganization",
  inheritAttrs: false,
});

interface SelectOption {
  id?: string;
}
const emit = defineEmits(["update:visible", "echo-info"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "成品物料";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Array,
    default: () => {
      return [];
    },
  },
  isMultiple: {
    type: Boolean,
    default: true,
  },
  plantId: {
    type: String,
    default: () => {
      return "";
    },
  },
  materialType: {
    type: String,
    default: () => {
      return "";
    },
  },
});

const { materialType, plantId, visible, isMultiple, title } = toRefs(props);

// 组织机构树
function resetParams() {
  searchParam.value = searchParamInit;

  // if (props.materialType) {
  //   searchParam.value.materialType = props.materialType;
  // }

  reset();
}

// 深层拷贝
function deepCopy(val: any) {
  return JSON.parse(JSON.stringify(val));
}

// 表格选择
const totalMultipleSelection: any = ref([]);
// 表格触发全选
function handleAllChange(selecteds: any) {
  if (isMultiple.value) {
    const currentSelection = deepCopy(totalMultipleSelection.value);
    const ids = deepCopy(totalMultipleIds.value);
    if (selecteds.length) {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.id);
        if (indexId < 0) {
          totalMultipleSelection.value.push(item);
        }
      });
    } else {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.id);
        if (indexId > -1) {
          currentSelection.splice(indexId, 1);
          ids.splice(indexId, 1);
        }
      });
      totalMultipleSelection.value = currentSelection;
    }
  } else {
    delAll();
    ElMessage.warning("单选，请重新选择");
  }
}
// 表格触发单个选择
function handleSelectionChange(val: any, row: SelectOption) {
  let addOptions = false;
  val?.map((item: SelectOption) => {
    if (item.id === row.id) {
      addOptions = true;
    }
  });
  if (!addOptions) {
    const index = totalMultipleIds.value.indexOf(row.id);
    totalMultipleSelection.value.splice(index, 1);
  } else {
    if (isMultiple.value) {
      totalMultipleSelection.value.push(row);
    } else {
      delAll();
      multipleTable.value.toggleRowSelection(row, true);
      totalMultipleSelection.value = [row];
    }
  }
}

// 右侧人员选择操作
const multipleTable = ref(ElTable);
// 全部清除
function delAll() {
  totalMultipleSelection.value = [];
  multipleTable.value.clearSelection();
}
// 单个删除
function delSingle(current: SelectOption, index: number) {
  totalMultipleSelection.value.splice(index, 1);
  tableData.value.map((item: SelectOption) => {
    if (item.id === current.id) {
      multipleTable.value.toggleRowSelection(item, false);
    }
  });
}

/** 弹窗展开 初始化数据 */
const totalMultipleIds: any = ref([]);
watch(
  () => totalMultipleSelection,
  async (newVal: any) => {
    const ids: any = [];
    newVal.value?.map((item: SelectOption) => ids.push(item.id));
    totalMultipleIds.value = ids;
  },
  { deep: true }
);

// 监听传过来的工厂id
watch(
  () => props.plantId,
  (newVal: string) => {
    console.log("s----plantId", newVal);
    searchParam.value.plantId = newVal;
    searchParamInit.plantId = newVal;
    if (props.plantId != "") {
      searchParam.value.plantId = props.plantId;

      if (props.materialType != "") {
        searchParam.value.materialType = props.materialType;
      }
      getTableList();
    } else {
      totalMultipleSelection.value = [];
    }
  }
);

// 请求参数
const requestApi = "mdm/mdmmaterial/selectRollMaterialProduction";
// mdm/mdmequipinfo/selectEquipInfo

// 是否需要分页
const pagination = true;

const initParam = reactive({});

// 初始化搜索参数数据
const searchParamInit = {
  plantId: "",
  materialGroupId: "",
  materialType: "",
  materialCode: "",
  materialName: "",
  figureNumber: "",
};

const isList = [
  {
    value: 2,
    label: "半成品",
  },
  {
    value: 5,
    label: "虚拟件",
  },
];

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
function dataCallBack(data: any) {
  setTimeout(() => {
    data.map((item: SelectOption) => {
      if (totalMultipleIds.value.includes(item.id)) {
        multipleTable.value.toggleRowSelection(item, true);
      }
    });
  }, 0);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  loading,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError
);

/** 弹窗展开 初始化数据 */
const oldTotalSelection: any = ref([]);
watch(
  () => props.visible,

  async (newVal: boolean) => {
    console.log(props.materialType);

    if (newVal) {
      totalMultipleSelection.value = deepCopy(props.data);
      oldTotalSelection.value = deepCopy(props.data);
      dataCallBack(tableData.value);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  totalMultipleSelection.value = oldTotalSelection.value;
  reset();
  dataCallBack(tableData.value);
  emit("update:visible", false);
}

/** 确定提交 */
async function handleSubmit() {
  if (!isMultiple.value && totalMultipleSelection.value.length > 1) {
    ElMessage.error("请选择单个人员");
  } else {
    emit("update:visible", false);
    emit("echo-info", totalMultipleSelection.value);
  }
}

// 物料组数据
const materialGroupTree = ref([]);
// 获取物料组数据
const getMaterialGroupTree = async () => {
  const res = await request({
    url: "mdm/mdmmatgroup/getList",
    method: "post",
    data: {},
  });
  materialGroupTree.value = res.data;
};

onMounted(() => {
  console.log(props.plantId);

  if (props.plantId != "") {
    searchParamInit.plantId = props.plantId;
    searchParam.value.plantId = props.plantId;
    getTableList();
  }
  getMaterialGroupTree();
}),
  // 组件销毁时调用
  onBeforeUnmount(() => {
    emit("update:visible", false);
    closeDialog();
  });
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding: 20px 20px 0 20px;
}
.name:hover {
  background-color: rgb(236, 245, 255) !important;
  color: var(--el-menu-active-color) !important;
  border-radius: 6px;
  svg {
    color: var(--el-menu-active-color) !important;
  }
}
.name svg {
  cursor: pointer;
}
:deep(.el-form--inline .el-form-item) {
  margin-right: 18px;
  margin-bottom: 14px;
}
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color))
    inset !important;
}
.el-button svg {
  margin-right: 0;
}
.card-table-p15 {
  :deep(.el-dialog__body) {
    padding: 15px;
  }
  .card-table {
    line-height: normal;
  }
}

:deep(.el-tree) {
  height: 533px;
}
</style>
